package com.hckjsec.common.ueditor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.baidu.ueditor.ActionEnter;
import com.hckjsec.common.init.YwInitData;
import com.hckjsec.common.ueditor.domain.CloudApiConfig;
import com.hckjsec.common.ueditor.domain.UploadImgConfig;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;


@RestController
// 前端配置的访问地址，必须和这里的相同，这样才能正确获取到ueditor配置
@RequestMapping("/ueditor")
public class UeditorController {
    private static final Logger log = LoggerFactory.getLogger(OssUtils.class);
    @Resource
    private UploadImgConfig uploadImgConfig;
    @Resource
    private CloudApiConfig cloudApiConfig;
    @Autowired
    private YwInitData ywInitData;
    /**
     * 获取ueditor配置信息时会走此方法
     * 由于ueditor并不能单独指定是通过那个URL获取配置
     * 而是通过URL后面携带的action参数来进行识别
     * 所以这里加上了if ("config".equals(action))的判断
     */
    @GetMapping
    public void config(HttpServletRequest request, HttpServletResponse response) throws JSONException {
        String action = request.getParameter("action");
        if ("config".equals(action)) {
            response.setContentType("application/json");
//            String rootPath = request.getSession().getServletContext().getRealPath("/");
//            String path = this.getClass().getClassLoader().getResourceAsStream("config.json").getPath();
            InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("config.json");
            try {
//                ActionEnter actionEnter = new ActionEnter(request, rootPath);
//                String exec = actionEnter.exec();
                PrintWriter writer = response.getWriter();
                writer.write(IOUtils.toString(stencilsetStream, "utf-8"));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                log.error("获取ueditor配置失败");
            }
        }
    }

    /**
     * 进行文件上传时
     * post方式会走这个方法
     * 这里并没有直接用JOSN.toJSONString方法来转换结果为json字符串
     * 因为查看了转换后的结果为{"state":true}
     * 这样的json字符串是不能被前端ueditor正确解析的
     * 所以采用了BaseState自己的toJSONString方法
     */
    @PostMapping
    public String upload(HttpServletRequest request) {
        List<MultipartFile> files = ((StandardMultipartHttpServletRequest) request).getMultiFileMap().get("upfile");
        MultipartFile file = CollectionUtils.isNotEmpty(files) ? files.get(0) : null;
        return OssUtils.uploadImg(cloudApiConfig, uploadImgConfig,ywInitData.getAccessUrlPrefix(), file).toJSONString();
    }
}

